const app = getApp()
/**
 * 购物车: 主页、搜索页、商品变动 公共方法
 * */
 function handleCommodityChange(spCarCommodityList = [], cItem, type, num = 0, del = false) {
  if (type === 3) spCarCommodityList = [] // 清空
  if (!spCarCommodityList || !cItem || (!type && type !== 0)) return spCarCommodityList;
    const cLast = spCarCommodityList.findIndex(item => item.cid === cItem.cid),
          isExist = cLast !== -1 ? true : false; // 是否存在
    if((!isExist) && (type === 1 || type === 2)){ // 不存在就直接加入购物车
      if (type === 2) { // 指定数量
        cItem.payNumber = num;
      } else if (type === 1) { // 添加
        cItem.payNumber++; // 先加
      }
      console.log('我被加入到购车里了', cItem, type)
      spCarCommodityList.push(cItem);
    } else {
      console.log('qdwqdw', del)
      spCarCommodityList = handleCommodityUpdata(spCarCommodityList, cItem.cid, type, num, del);
    }
    return spCarCommodityList;
 }

  /**
   * 商品列表: 主页、搜索页、商品变动 公共方法
   * */
  function handleCommodityListChange(commodityList = [], cid, type, num = 0, del = false) {
    if (!commodityList || !cid || (!type && type !== 0)) return;
      const resultCommodityList = commodityList.map(item => {
        item.cdList = handleCommodityUpdata(item.cdList, cid, type, num,  del);
        return item;
      });
      return resultCommodityList;
  }
  // 更新商品数量
  function handleCommodityUpdata(list, cid, type, num = 0, del = true) { // del商品等于0是否移除
    if (!list) return list
    const findLast = list && Array.isArray(list) && list.findIndex(it => it.cid === cid);
    console.log('dwqdw', findLast, type)
    if (findLast !== undefined && findLast !== -1) {
      if (type === 1) { // 加 
        list[findLast].payNumber++;
      } else if (type === 0) { // 减
        list[findLast].payNumber <= 0 || list[findLast].payNumber--;
        del && list[findLast].payNumber <= 0 && list.splice(findLast, 1);
      } else if (type === 2) { // 更改指定数量
        list[findLast].payNumber = num;
      }
    }
    return list;
  }
  // 处理判断商品是否都为0 -> 用于隐藏购物车组件
  function getOnCommodityNumberIsZero() {
    const cData = getNewShoppingCarData() 
    return cData.filter(it => it.payNumber > 0).length === 0
  }

  // 获取全局状态最新购物车里的数据
  function getNewShoppingCarData() {
    return getStateVal('shoppingCarCommodityList');
  }
  // 设置全局状态为最新购物车数据
  function setNewShoppingCarData(val) {
    const key = 'shoppingCarCommodityList'
    setStateVal({ [`${key}`]: val });
    // 发送已更新的通知
    return wx.$emit('carListDataUpdata', app.store.getState()[key])
  }
  // 获取某属性的全局状态值
  function getStateVal(key) {
    return app.store.getState()[key];
  }
  // 设置某属性全局状态值
  function setStateVal(params = {}) {
    return app.store.setState(
      params
    );
  }

 module.exports = {
  handleCommodityChange,
  handleCommodityListChange,
  getNewShoppingCarData,
  getOnCommodityNumberIsZero,
  setNewShoppingCarData,
  getStateVal,
  setStateVal
 };